use hypers::hyper::StatusCode;
use hypers::prelude::*;
use rust_embed::RustEmbed;

#[derive(RustEmbed)]
#[folder = "static"]
struct Assets;

/*
   127.0.0.1:7878/images/head.webp
   127.0.0.1:7878/images/icon.jpg
   127.0.0.1:7878/css/index.css
   127.0.0.1:7878/css/login.css
*/
async fn serve_file(req: Request) -> Response {
    let mut res = Response::default();
    let path = req.param::<String>("*1").unwrap();
    if let Some(file) = Assets::get(&path) {
        render_embedded_file(file, &req, &mut res, None);
        res
    } else {
        res.render(StatusCode::NOT_FOUND)
    }
}

#[tokio::main]
async fn main() -> Result<()> {
    let mut root: Router = Router::default();
    /*
        浏览器输入
        127.0.0.1:7878/static_embed/images/head.webp
        127.0.0.1:7878/static_embed/images/icon.jpg
        127.0.0.1:7878/static_embed/css/index.css
        127.0.0.1:7878/static_embed/css/login.cs
    */
    let static_embed = StaticEmbed::<Assets>::new().fallback("images/icon.jpg");
    root.get("/static_embed/*", static_embed); // 127.0.0.1:7878/static_embed/images/head.webp
    /*
        浏览器输入
        127.0.0.1:7878/images/head.webp
        127.0.0.1:7878/images/icon.jpg
        127.0.0.1:7878/css/index.css
        127.0.0.1:7878/css/login.css
    */
    root.get("/*", serve_file);
    println!("root = {:#?}", root);
    let listener = hypers::TcpListener::bind("127.0.0.1:7878").await?;
    hypers::listen(root, listener).await
}

